;(function(w) {

  var app = new Vue({
    el: '#businessDispatch',
    data: {
      listMenu: [
        {
          name: '待分派',
          code: 'WFP',
          num:0
        },
        {
          name: '已分派',
          code: 'YFP',
          num:0
        }
      ],
      selectedListMenuCode: [],
      keyWord:null,
      rperson: { name:null, list:[], id:null }, // 对接人
      rpersonKeyword:null,
      limit:['10'],
      currentPage: 1,
      totalCount:0,
      totalPage: 0,
      pageCounts: [{name: '10', code: '10'}, {name: '15', code: '15'}, {name: '20', code: '20'}],
      industryType:[],
      selectedIndustryType: [],
      customerStatuList:[
        
      ],
      selectedCustomerStatu: [],
      customerType:[{'name':'全部','code':'#'},{'name':'公司','code':'QY'},{'name':'个人','code':'PE'}],
      selectedCustomerType: [],
      channelType: [], //渠道分类
      selectedChannelType: [],
      channelName: [],  //渠道名称
      selectedChannelName: [],
      sourceList: [], //商机来源
      selectedSource:{ 'name':null , 'code':null },
      positionList:[],
      personList: [],
      listData:[],
      countInfoData:[],
      excelURI:'javascript:;',
      isShowPersonLayer:false,
      isShowSelector:false,
      isShowOperationBar:true,
      selectedMulItem:{sjIds:[],id:null,name:null},
      selectedOrg: {
        id: null,
        name: null
      },
      assigneeIdArr:[],
      isAllSelected:false,
      isExtenseFlag:false,
      quanxian: JSON.parse(localStorage.getItem('permissions')),
			configType: 'WZ', //默认完整WZ     JD简单，WZ完整，自定义配置PZ
			module: '#',
			headArr: [],
			sortTableTitle: [],
			isScroll: false,
			isShowTableLayer: false,
			dateTimeUpdate: [],
      isActiveCode: '#',
      tbTitleWidth:{},
      listObj:{
        customerAssigns:[]
      },
      columns:'',
      orders:'',
    },
    filters: {
      formatYYYYMMddHHmmss(item){
        if(!item) return '--'
        return hlDateUtil.formatUTCDate(item, 'yyyy-MM-dd HH:mm:ss')
      },
      formatUndefined: function(item) {
			  if (!item) return '--'
				if (typeof item == 'number') {
					if (!isNaN(item) && item.toString().length == 13) {
						return hlDateUtil.formatUTCDate(item, 'yyyy-MM-dd HH:mm')
					};
				}
			  return item
			},
    },
    methods: {
			ZS_CUSTOMER_STATUS() {
			    var self = this
			    hlhttp.get({
			        url: 'configure/dict',
			        data: { module_code: 'ZHSH', config_name: 'ZS_CUSTOMER_STATUS' },
			        success: data => {
								data.unshift({dictName: '全部', dictCode: '#'})
			            self.customerStatuList = hlArrayUtil.replaceData(data, [{ key: 'dictName', rKey: 'name' }, { key: 'dictCode', rKey: 'code' }])
			        }
			    })
			},
      selectMenuList(){
        this.currentPage = 1
        this.searchData()
      },
       // 表头中是否全选方法
      isAllSelect(item){
        if(this.selectedMulItem.sjIds.length == this.listObj.customerAssigns.length){
          this.selectedMulItem.sjIds = []
        }else{
          this.selectedMulItem.sjIds = []
          this.listObj.customerAssigns.map(item =>{
            this.selectedMulItem.sjIds.push(item.id)
          })
        }
      },
      // 单个选择
      selectDispatchItem(item){
        let num = this.selectedMulItem.sjIds.indexOf(item)
        if( num == -1){
          this.selectedMulItem.sjIds.push(item)
        }else{
          this.selectedMulItem.sjIds.splice(num,1)
        }
      },
      // 获取当前用户所在的岗位列表
      getUserPositions(){
        hlhttp.get({
          url: 'organization/user_positions',
          data:{show_suborg:'Y'},
          success: data => {
            this.positionList = data;
          }
        })
      },
      // 操作区分派按钮方法
      dispatchBusiness(id){
        this.selectedMulItem.sjIds.push(id);
        this.isShowPersonLayer = true;
        this.selectedMulItem.id = ''
        this.selectedMulItem.name = ''
        this.personList = []
        $('.org-name').html('请选择')
        $('.person-name').html('请选择')
      },
      closePersonLayer() {
        this.isShowPersonLayer = false;
        this.selectedMulItem.sjIds = []
        this.selectedMulItem.id = ''
        this.selectedMulItem.name = ''
      },
      singleItemSelectProject(item) {
        var that = this;
        hlhttp.get({
          url: 'organization/admin_position_users',
          data: {
            'position_id': item.positionId,
            'is_admin': item.isAdmin
          },
          success: data => {
            that.personList = data;
            that.selectedMulItem.name = ''
            that.selectedMulItem.id = '';
            that.$refs.DJR.innerHTML = '请选择'
          }
        })
      },
      singleItemSelectPerson(item) {
        this.selectedMulItem.id = item.userId;
        this.selectedMulItem.name = item.userName;
      },
      // 确定分派的方法
      confirmDispatchSingleItem(){
        if(!this.selectedMulItem.id){
          hl.toast('请选择对接人')
          return
        }
        if(!this.selectedMulItem.sjIds.length){
          hl.toast('请选择客户')
          return
        }
        hlhttp.put({
          url:'customer_assign',
          data:{customer_ids:this.selectedMulItem.sjIds.join(','),assignee_id:this.selectedMulItem.id,assignee_name:this.selectedMulItem.name},
          success:data => {
            hl.toast('分派成功')
            this.isShowPersonLayer = false;
            this.isShowSelector = false;
            this.selectedMulItem.sjIds = []
            this.selectedMulItem.id = ''
            this.selectedMulItem.name = ''
            this.search()
          }
        })
      },
      // 批量分派按钮
      batchDispatch(){
        this.isShowSelector = !this.isShowSelector
        this.personList = []
        this.selectedMulItem = {
          sjIds: [],
          id: '',
          name: ''
        }
        this.getUserPositions();
      },
      // 去详情
      goTodetail(id){
        hlUrlUtil.goTo('customerDetails',{'id':id,'ddtab':true,'page':'customerDispatch'},true)
      },
      resetTabbar(){
        this.selectedListMenuCode = []
        this.currentPage = 1
        this.searchData()
      },
      openSearch:function(){
        if(this.isExtenseFlag == true){
          this.isExtenseFlag = false;
          return false;
        }
        if(this.isExtenseFlag == false){
          this.isExtenseFlag = true;
          return false;
        }
      },
      searchData(){
        var self = this;

        var submitData = {
          'keyword':self.keyWord || '#',
          'customer_status':self.selectedCustomerStatu.length ? self.selectedCustomerStatu[0] : '#',
          'customer_type':self.selectedCustomerType.length ? self.selectedCustomerType[0] : '#',
          'rperson_id':self.rperson.id || '#',
          "industry_code":self.selectedIndustryType.length ? self.selectedIndustryType[0] : '#',
          'channel_category_code':self.selectedChannelType.length ? self.selectedChannelType[0] : '#',
          'channel_name_code':self.selectedChannelName.length ? self.selectedChannelName[0] : '#',
          'assign_status':self.selectedListMenuCode.length ? self.selectedListMenuCode.join(',') : '#',
          'limit':self.limit[0],
          'page':self.currentPage,
          'columns':self.columns || '#',
          'orders':self.orders || '#',
        }

        hlhttp.get({
          url:'customer_assign_search',
          data:submitData,
          success:function(data){
            data.customerAssigns.map(item =>{
              item.iSselect = true
            })
            self.listObj = data
            data.customerAssigns.forEach(el => el['isChecked'] = 'N')
            self.listData = data.customerAssigns
            self.totalCount = data.totalCount
            self.totalPage = data.totalPage
            self.countInfoData = data.countInfo
            self.listMenu.forEach(el => {
              if(el.code == 'WFP') el['num'] = data.countInfo.WFP;
              if(el.code == 'YFP') el['num'] = data.countInfo.YFP;
            })

          }
        })
      },
      //查询
      search(){
        this.currentPage = 1;
        this.limit = ['10'];
        this.searchData()
      },
      reset(){
        this.columns = '#'
        this.orders = '#'
        this.isActiveCode = '',
        this.keyWord = null;
        this.selectedChannelType = []
        this.selectedChannelName = []
        this.selectedCustomerStatu = []
        this.selectedCustomerType = []
        this.selectedIndustryType = []
				this.channelName = []

        this.rperson = { name:null, list:[], id:null };
        this.search()
      },
      // 获取对接人人员列表
      getRpersonData(){
        var self = this;
        hlhttp.get({
          url:'data_group/users/_search',
          data:{'keyword':self.rperson.name || '#'},
          success:function(data){
            self.rperson.list = data;
            // 自动匹配  当输入的名字跟下拉列表中名字匹配时  则存储ID
            data.forEach(el => {
              if(el.userName == self.rpersonKeyword){
                self.rperson.name = self.rpersonKeyword;
                self.rperson.id = el.userId;
              }
            })
          }
        })
      },
      // 设置对接人name，获取id
      setRperson(name,id){
        this.rperson = { name:name, list:[], id:id }
        this.rpersonKeyword = name
      },
      hideRpersonList(){
        this.rperson.list = [];
      },
      selectCustomerStatu(arr){
        this.selectedCustomerStatu = [arr[0].code]
      },
      selectCustomerType(arr){
        this.selectedCustomerType = [arr[0].code]
      },
      // 获取产业
      getIndustryType(){
        hlhttp.get({
          url:'configure/industry/dict',
          success:data => {
            data.unshift({'dictName':'全部','dictCode':'#'})
            this.industryType = hlArrayUtil.replaceData(data, [{key: 'dictName', rKey: 'name'}, {key: 'dictCode', rKey: 'code'}]);
          }
        })
      },
      selectIndustryType(arr){
        this.selectedIndustryType = [arr[0].code]
      },
      // 渠道分类
      getChannelType() {
        hlhttp.get({
          url: 'configure/dict',
          data: {module_code: 'ZHSH', config_name: 'ZS_CHANNEL_CATE'},
          success: data => {
            this.channelType = hlArrayUtil.replaceData(data, [{key: 'dictName', rKey: 'name'}, {key: 'dictCode', rKey: 'code'}]);
          }
        })

      },
      selectChannelType(arr) {
        this.selectedChannelType = [arr[0].code]
				this.getChannelName()
      },
      // 获取渠道名称
      getChannelName() {
        hlhttp.get({
          url: 'configure/dict',
          data: {module_code: 'ZHSH', config_name: 'ZS_CHANNEL_NAME'},
          success: data => {
            this.channelName = hlArrayUtil.replaceData(data, [{key: 'dictName', rKey: 'name'}, {key: 'dictCode', rKey: 'code'}]);
          }
        })

      },
      selectChannelName(arr){
        this.selectedChannelName = [arr[0].code]
      },
      //商机来源
      getSJsource () {
        hlhttp.get({
          url: 'configure/dict',
          data: {module_code: 'ZHSH0SHJI', config_name: 'SJ_SOURCE'},
          success: data => {
            data.unshift({'dictName':'全部','dictCode':'#'})
            this.sourceList = hlArrayUtil.replaceData(data, [{key: 'dictName', rKey: 'name'}, {key: 'dictCode', rKey: 'code'}]);
            this.selectedSource = [data[0].code]
          }
        })
      },
      selectSJsource(arr){
        this.selectedSource = [arr[0].code]
      },
      selectPerNum(arr){
        this.limit = [arr[0].code]
        this.currentPage = 1
        this.searchData()
      },
      //更新时间
      sortBySTTime (item) {
        if(this.dateTimeUpdate.indexOf(item.value) == -1) return
        this.isActiveCode = item.value;
        this.orders = this.orders == 'ASC' ? 'DESC' : 'ASC';
        this.columns = item.orderName
        this.searchData()
      },
      //获取自定义表头配置状态
			configTypeDt () {
				hlhttp.get({
					url: 'configure/customize_column_header/type',
					data: {module: 'ZHSH_KHFP'},
					success: (data) => {
						this.configType = data.configType;
						this.customizeHeaderDt()
					}
				})
			},
			//获取自定义表头配置信息
			customizeHeaderDt () {
				hlhttp.get({
					url: 'configure/customize_column_header',
					data: {module: 'ZHSH_KHFP'},
					success: (data) => {
						data.customConfigList.map(item => {
							item.seq = Number(item.seq)
							item.customSeq = Number(item.customSeq)
              item.isActive = 'N'
              if (item.orderFlag == 'Y') {
								this.dateTimeUpdate.push(item.value)
							}
						})
						if (this.configType == 'JD' || this.configType == 'WZ') {
              data.customConfigList = data.customConfigList.sort(hlArrayUtil.compareAsc('seq'))
              data.customConfigList.unshift({
                value : 'iSselect',
                name:'全选',
                baseFlag:'Y',
                isChecked:'N',
              })
						}
						if (this.configType == 'PZ') {
              data.customConfigList = data.customConfigList.sort(hlArrayUtil.compareAsc('customSeq'))
              data.customConfigList.unshift({
                value : 'iSselect',
                name:'全选',
                customShowFlag:'Y',
                isChecked:'N'
              })
						}
            this.headArr = JSON.parse(JSON.stringify(data.customConfigList));
            this.sortTableTitle = JSON.parse(JSON.stringify(data.customConfigList));
            this.sortTableTitle.splice(0,1)
						this.tbTitleWidthCalculation()
					}
				})
			},
			//宽度计算
			tbTitleWidthCalculation () {
				let w = 0, flag = false;
				this.headArr.map(item => {
					if (item.value == '序') {
						flag = true;
					}
				})
        w = this.headArr.length * 120 - 80;
        if(w < 855){
          w = 855
        }
				this.tbTitleWidth = {width: w+ 'px'}
			},
			//弹窗显示
			showTableLayer() {
				this.isShowTableLayer = true;
      },
			//关闭自定义表头弹窗
			closeTableLayer() {
        this.isShowTableLayer = false;
      },
			//简单完整配置切换
			selectTableType(type) {
        this.configType = type;
				this.changeTableType(type)
				this.updateConfigType()
      },
			//更新自定义表头配置状态
			updateConfigType () {
				hlhttp.put({
					url: 'configure/customize_column_header/type',
					data: {module: 'ZHSH_KHFP', config_type: this.configType},
					success: () => {
						this.configTypeDt()
					}
				})
			},
			//改变头部
			changeTableType (type) {
				console.log(type)
				if (type == 'JD' || type == 'WZ') {
					this.headArr = this.headArr.sort(hlArrayUtil.compareAsc('seq'))
				}
				if (type == 'PZ') {
					this.headArr = this.headArr.sort(hlArrayUtil.compareAsc('customSeq'))
				}
				this.tbTitleWidthCalculation()
			},
			//显示某个自定义标题
			selectedTitleItem(i) {
        this.sortTableTitle[i].customShowFlag = 'Y'
      },
			//关闭某个自定义标题
      cancelSelectedTitleItem(i) {
        this.sortTableTitle[i].customShowFlag = 'N'
      },
			showhighLightTitleItem(el, i) {
				this.sortTableTitle[i].isActive = 'Y'
      },
      removehighLightTitleItem(el, i) {
				this.sortTableTitle[i].isActive = 'N'
      },
			//鼠标经过显示scroll
			showScroll() {
        this.isScroll = true;
      },
			//鼠标离开关闭scroll
      hideScroll() {
        this.isScroll = false;
      },
			// 确定提交自定义表格
      confirmSubmitTable() {
        let dataArr = [];
				this.sortTableTitle.map((item, index) => {
					dataArr.push({
            "base_flag": item.baseFlag,
            "seq": item.seq,
            "custom_show_flag": item.customShowFlag,
            "custom_seq": index,
            "custom_display_name": item.customDisplayName ? item.customDisplayName : '#',
            "dict_code": item.dictCode,
            "config_type": item.configType,
            "name": item.name,
            "value": item.value,
            "union_table_part": item.unionTablePart,
            flex: item.flex,
            style_width: item.styleWidth,
            order_flag: item.orderFlag,
            order_name: item.orderName
					})
				})
				hlhttp.put({
					url: 'configure/customize_column_header',
					data: {
						module: 'ZHSH_KHFP',
						custom_config: JSON.stringify(dataArr)
					},
					success: (data) => {
						hl.toast('操作成功')
						this.closeTableLayer()
						this.updateConfigType()
					}
				})
      },
      // 初始化拖动排序
      initSortable() {
        const self = this;
        const el = document.getElementById('sortableTable');
        Sortable.create(el, {
          draggable: 'ul',
          onEnd(evt) {
            const beginIndex = evt.oldIndex;
            const endIndex = evt.newIndex;
            const newArr = JSON.parse(JSON.stringify(self.sortTableTitle));
            newArr.splice(endIndex, 0, newArr.splice(beginIndex, 1)[0])
            self.sortTableTitle = [];
            self.$nextTick(() => {
              self.sortTableTitle = newArr
            })
          }
        })
      },
    },
    mounted: function() {
      hlSelectUi()
      this.initSortable();
      this.configTypeDt();
			this.getChannelType()
			this.getIndustryType()
      this.search()
      this.getSJsource()
      this.getUserPositions()
			this.ZS_CUSTOMER_STATUS()
    }
  })

}(window))
